package com.zhz.mall.common.constraints;

import cn.hutool.core.collection.CollUtil;
import com.zhz.mall.common.annotation.TypeLevelValid;
import lombok.Builder;
import lombok.Data;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * @author zhouhengzhe
 */
public abstract class TypeLevelValidator<T> implements ConstraintValidator<TypeLevelValid, T> {
    @Override
    public boolean isValid(T value, ConstraintValidatorContext context) {
        List<ValidResult> valid = valid(value);
        if (CollUtil.isEmpty(valid)) {
            return true;
        }
        context.disableDefaultConstraintViolation();
        valid.forEach(temp -> context.buildConstraintViolationWithTemplate(temp.getTemplate())
                .addPropertyNode(temp.getPropertyNode())
                .addConstraintViolation());
        return false;
    }

    protected abstract List<ValidResult> valid(T t);

    @Data
    @Builder
    public static class ValidResult {
        private String template;
        private String propertyNode;
    }
}
